package com.easy.orm.jdbc.support;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.easy.orm.jdbc.ResultSetExtractor;
import com.easy.orm.jdbc.RowMapper;

/**
 * <b> 返回 List RowMapper</b>
 * 
 * @see com.easy.orm.jdbc.ResultSetExtractor
 * @see com.easy.orm.jdbc.RowMapper
 * 
 * @author kun
 *
 * @param <T> 处理返回行结果
 */
public class RowMapperResultSetExtractor<T> implements ResultSetExtractor<List<T>> {

	/**
	 * 数据行处理对象
	 */
	private final RowMapper<T> rowMapper;

	/**
	 * 预期处理结果
	 */
	private final int rowsExpected;

	/**
	 * <b> 实例化</b>
	 * 
	 * @param rowMapper 数据行处理对象
	 */
	public RowMapperResultSetExtractor(RowMapper<T> rowMapper) {
		this(rowMapper, 16);
	}

	/**
	 * <b> 实例化</b>
	 * 
	 * @param rowMapper 数据行处理对象
	 * @param rowsExpected 预期处理结果
	 */
	public RowMapperResultSetExtractor(RowMapper<T> rowMapper, int rowsExpected) {
		super();
		this.rowMapper = rowMapper;
		this.rowsExpected = rowsExpected;
	}

	/**
	 * ResultSet 处理
	 * 
	 * @param rs rs {@linkplain java.sql.ResultSet}
	 * @return ResultSet 处理结果
	 * @throws SQLException 处理异常
	 */
	@Override
	public List<T> extractData(ResultSet rs) throws SQLException {

		// 实例化返回 容器
		List<T> results = new ArrayList<>(this.rowsExpected);

		// 处理 ResultSet
		int rowNum = 0;
		while (rs.next()) {
			results.add(this.rowMapper.mapRow(rs, rowNum++));
		}

		// 返回
		return results;
	}

}
